import axios from 'axios';

export const apiBaseUrl = window.g.apiType == 1 ? window.g.api : window.location.origin;

axios.defaults.baseURL = apiBaseUrl;
// 请求超时时间
axios.defaults.timeout = window.g.axiosTimeout;
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json';

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    config.headers.Authorization = "Bearer "+ token;
    config.headers.apiPath = apiBaseUrl;
    return config;
  }
);

axios.interceptors.response.use(
  response => {
    return response.data;
  },error => {
    if(error.code === 'ECONNABORTED' ||  error.message.includes("timeout")){
      error.msg = "连接超时";
    } else if (error.message ===   "Network Error") {
      error.msg = "网络错误";
    } else if (error.message === "Request failed with status code 404") {
      let url = error.config ? error.config.url : null;
      if (url) {
        error.msg = "接口[" + url + "]不存在"
      } else {
        error.msg = "接口不存在"
      }
    } else if (error.message === "Request failed with status code 500") {
      error.msg = "系统异常"
    }
    if (!error.message) {
      error.msg = "系统异常";
    }
    return error;
  }
);

export function post(url, params = {}) {
  if (window.g.apiPrefix) {
    url = window.g.apiPrefix + url;
  }
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(res => {
      if (res.code == 401) {
        window.location.href = "/#/login"
      }
      resolve(res);
    }).catch(err => {
      console.error(err);
      resolve(err);
    })
  })
}

export function get(url, params = {}){
  if (window.g.apiPrefix) {
    url = window.g.apiPrefix + url;
  }
  return new Promise((resolve, reject) =>{
    axios.get(url, {
      params: params
    }).then(res => {
      if (res.code == 401) {
        window.location.href = "/#/login"
      }
      resolve(res);
    }).catch(err => {
      console.error(err);
      resolve(err);
    })
  });
}

export function parseParams(paramsMap) {
  try {
    let paramArr = [];
    Object.keys(paramsMap).map(function (key) {
      if (paramsMap[key] != null) {
        paramArr.push(key + "=" + encodeURIComponent(paramsMap[key]))
      }
    });
    return paramArr.join('&');
  } catch (err) {
    return '';
  }
}
